package com.sprboot.demo.conf;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 实体管理器及事务管理器配置
 * 
 * @author yangli
 *
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryPrimary", transactionManagerRef = "transactionManagerPrimary", basePackages = {
		"com.sprboot.demo.domain.repository.first" })
public class RepositoryPrimaryConfig {
	// DataSource, LocalContainerEntityManagerFactoryBean
	// EntityManager,PlatformTransactionManager
	@Autowired
	private JpaProperties jpaProperties;
	@Autowired
	@Qualifier("primaryDS")
	private DataSource primaryDS;

	@Bean(name = "entityManagerPrimary")
	@Primary
	public EntityManager entityManagerPrimary(EntityManagerFactoryBuilder builder) {
		return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
	}

	@Bean(name = "transactionManagerPrimary")
	@Primary
	PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
	}

	@Bean(name = "entityManagerFactoryPrimary")
	@Primary
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
		
		return builder.dataSource(primaryDS).properties(jpaProperties.getProperties())
				.packages("com.sprboot.demo.domain.vo.first") // 设置实体类所在位置
				.persistenceUnit("primaryPersistenceUnit").build();
	}

}
